﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DotNetExtensions.Core.Helpers
{
    public class Combination
    {
        public static List<List<T>> Create<T>(List<T> elements, int m)
        {
            List<List<T>> list = new List<List<T>>();
            T oneElment;
            List<T> source = new List<T>(elements);
            int n = 0;

            if (elements != null)
            {
                n = elements.Count;
            }
            if (n == m && m != 1)
            {
                list.Add(source); return list;
            }
            List<T> oneList;
            if (m == 1)
            {
                foreach (T el in source)
                {
                    oneList = new List<T>();
                    oneList.Add(el);
                    list.Add(oneList);
                    oneList = null;
                }
                return list;
            }

            for (int i = 0; i <= n - m; i++)
            {
                oneElment = source[0];
                source.RemoveAt(0);
                List<List<T>> temp = Create(source, m - 1);
                for (int j = 0; j < temp.Count; j++)
                {
                    oneList = new List<T>();
                    oneList.Add(oneElment);
                    oneList.AddRange(temp[j]);
                    list.Add(oneList);
                }
            }
            return list;
        }
    }
}
